import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'
import { useRouter } from 'vue-router'
import { getToken } from '@utils/index'
import { ElMessage } from 'element-plus'
console.log(getToken, 'getTokengetToken')
const router = useRouter()

export const instance = axios.create()

instance.defaults.timeout = 10000

// prettier-ignore
instance.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"

axios.interceptors.request.use(
  (config) => {
    const token = getToken()
    console.log('请求拦截--config', config)
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    // console.log("请求拦截--error", error)
    return error
  }
)

// 响应拦截
axios.interceptors.response.use(
  (res) => {
    console.log('响应拦截--response', res)
    // if (res.data.code === 111) {
    //   sessionStorage.setItem("token", "")
    //   // token过期操作
    // }
    // if (res?.data?.code === -1 && res?.data?.message) {
    //   // console.log("弹窗", res.data.message)
    //   ElMessage.warning(res?.data?.message || '请求失败，请稍后重试')
    // }
    return res
  },
  (error) => {
    // console.log("响应拦截--error", error)
    if (error.response.status === 401) {
      ElMessage.warning('登录失效,请重新登录')
      setTimeout(() => {
        router.push('/login')
      }, 1000)
    } else if (error.response.status === 500) {
      // window.$message.warning("服务端错误，请稍后重试")
      router.push('/500')
    } else {
      // eslint-disable-next-line no-lonely-if
      if (error.response.data.code === -1 && error.response.data.message) {
        ElMessage.warning(error.response.data.message)
      }
    }
    return Promise.resolve(error.response.data)
  }
)

export async function postRequest<T>(
  url: string,
  data?: any,
  opt?: AxiosRequestConfig
): Promise<Resp<T>> {
  const res = await instance.post(url, data, opt)
  return res.data
}

export async function getRequest<T>(
  url: string,
  opt?: AxiosRequestConfig
): Promise<Resp<T>> {
  const res = await instance.get(url, opt)
  return res.data
}
